#pragma once

#define NUM_PIPES_PER_SERVER 3
#define NUM_RESOURCE_TYPES 2

enum PipeState
{
	PipeStateConnecting,
	PipeStateReading,
	PipeStateWriting
};

struct PipeInstance
{
	OVERLAPPED oOverlap;
	HANDLE hPipe;
	unsigned int uiRequest;
	DWORD dwBytesRead;
	bool bReply;
	DWORD dwBytesToWrite;
	PipeState eState;
	BOOL bPendingIO;
};

class Server
{
protected:
	char m_chPipeName[256];

	HANDLE m_hStopMutex;
	HANDLE m_hStopEvent;
	HANDLE m_hProcessSemaphore;

	long m_lResources[NUM_RESOURCE_TYPES];
	int m_iLastResourceSelection;

	bool m_bStopped;

	bool ConnectToNewClient(HANDLE hPipe, LPOVERLAPPED lpOverlapped);
	void DisconnectAndReconnect(PipeInstance& piPipeInstance);
	void GetAnswerToRequest(PipeInstance& piPipeInstance);

public:
	Server(const char* pPipeName);
	~Server();

	void Process();
	inline HANDLE GetProcessSemaphore() { return m_hProcessSemaphore; }

	void AddResources(int iResourceIndex, long lCount);

	void RunThread();

	static DWORD WINAPI ThreadFunction(LPVOID param);

	void Stop();
	bool IsStopped();
};

